/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package db;

import db.op.web.LoginOP;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author meluo
 */
public abstract class DBUtils {

    private static DataSource pool;
    private Connection conn;
    private Statement state;
    private ResultSet rest;
   

    static {
        Context env = null;
        try {
            env = (Context) new InitialContext().lookup("java:comp/env/");
            pool = (DataSource) env.lookup("testcashDB");
            if (null == pool) {
                System.err.println("'DBPool' is an unknown DataSource");
            }
        } catch (NamingException ne) {
        }
    }

    public Connection getConnection() throws SQLException {
        if(conn==null){
            conn=pool.getConnection();
        }
        return conn;
    }

    public Statement getStatement() throws SQLException {
        if (state == null) {
            state = getConnection().createStatement();
        }
        return state;
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        if (rest != null) {
            rest.close();
        }
        rest = getStatement().executeQuery(sql);
        return rest;
    }
    public ResultSet prepareExecuteQuery(PreparedStatement prepareStatement) throws SQLException{
        if (rest != null) {
            rest.close();
        }
      rest=prepareStatement.executeQuery();
        return rest;
    }
    
    public int prepareExecuteUpdate(PreparedStatement prepareStatement) throws SQLException{
        
        return prepareStatement.executeUpdate();
    }
    
    public int executeUpdate(String sql) throws SQLException {
        return getStatement().executeUpdate(sql);
    }
    public void onDestroy(){
        try {
            if(rest!=null){
            rest.close();
            }
            if(state!=null){
            state.close(); 
            }
            if(conn!=null){
            conn.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
